package dd.prog2.exercises.set14;

import java.io.File;
import java.io.FilenameFilter;

public class FileFinder {

	private File[] imageList = null; // jpg or jpeg files in current directory
	private int currentImage = 0; // current image index in the imageList

	public FileFinder(File path) {
		String p = path.getAbsolutePath();
		imageList = new File(p).listFiles(new FilenameFilter() {
			public boolean accept(File f, String name) {
				name = name.toLowerCase();
				return name.endsWith(".jpg") || name.endsWith(".jpeg");
			}
		});
	}

	public File next(File file) {
		File next = null;
		if (imageList.length > 0) {
			currentImage++;
			if (currentImage > imageList.length - 1)
				currentImage = 0;
			next = imageList[currentImage];
		}
		return next;
	}

	public File prev(File file) {
		File prev = null;
		if (imageList.length > 0) {
			currentImage--;
			if (currentImage < 0)
				currentImage = imageList.length - 1;
			prev = imageList[currentImage];
		}
		return prev;
	}

	/*
	 * finds selected image in imageList and saves its index in currentImage
	 */
	public void setCurrent(File file) {
		String fileName = file.getName();
		if (imageList != null) {
			for (int i = 0; i < imageList.length; i++) {
				if (imageList[i].getName().equals(fileName)) {
					currentImage = i;
				}
			}
		}
	}

}
